//
//  WLSegmentTitleView.m
//  LiveEducation
//
//  Created by Liu,Qingcan on 2017/4/16.
//  Copyright © 2017年 Baidu. All rights reserved.
//

#import "WLSegmentTitleView.h"
#import "UIView+WLExtension.h"

static CGFloat const normal_font = 15;
static CGFloat const normal_indicator_height = 2;
static CGFloat const normal_indicator_trans_duration = 0.15f;
static CGFloat const normal_text_scale = 0.14f;
static CGFloat const normal_button_margin = 12.f;



@interface WLSegmentTitleView()
@property(nonatomic,strong)NSArray *titleArray;
@property(nonatomic,assign,getter=isScaleText)BOOL scaleText;
@property(nonatomic,strong)UIButton *titleBtn;
@property(nonatomic,assign,getter=isFirstButton)BOOL firstButton;
@property(nonatomic,strong)UIView *indicatorView;


@property (nonatomic,strong)NSMutableArray *storageArray;


@property (nonatomic,strong)UIButton *tempButton;
@property (nonatomic,assign)NSInteger oldPosition;

@property (nonatomic, assign) BOOL titleViewCannotScroll;

@end

@implementation WLSegmentTitleView
@synthesize titleColor=_titleColor,titleSelectColor=_titleSelectColor;

#pragma mark life circle
- (instancetype)initWithFrame:(CGRect)frame delegate:(id)delegate childTitles:(NSArray *)title isScaleTitleText:(BOOL)isScale isScroll:(BOOL)isScroll{
    self = [super initWithFrame:frame];
    if (self) {
        self.titleArray = title;
        self.scaleText = isScale;
        self.wl_delegate = delegate;
        self.titleViewCannotScroll = !isScroll;
        self.frame = frame;
        
        self.showsVerticalScrollIndicator = NO;
        self.showsHorizontalScrollIndicator = NO;
        self.bounces = NO;
        [self setupViews];
        
    }
    return self;
}

+ (instancetype)initWithFrame:(CGRect)frame delegate:(id)delegate childTitles:(NSArray *)title isScaleTitleText:(BOOL)isScale isScroll:(BOOL)isScroll{
    return [[self alloc]initWithFrame:frame delegate:delegate childTitles:title isScaleTitleText:isScale isScroll:isScroll];
}


#pragma mark UIScrollViewDelegate



#pragma mark 位置切换
- (void)sureSelectedBtnLocation:(UIButton *)selecteBtn{
    //button
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(normal_indicator_trans_duration *0.5* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (!_tempButton) {
            selecteBtn.selected = YES;
            _tempButton = selecteBtn;
        }else if (_tempButton && _tempButton == selecteBtn){//
            selecteBtn.selected = YES;
        }else if (_tempButton && _tempButton!= selecteBtn){//空中
            selecteBtn.selected = YES;
            _tempButton.selected = NO;
            _tempButton = selecteBtn;
        }//空中
        
    });
    
    //指示器
    if (_segmentStyle == WLSegmentTitleStyleBottomIndicatorLine) {
        [UIView animateWithDuration:normal_indicator_trans_duration animations:^{
            _indicatorView.WL_width = selecteBtn.WL_width - normal_button_margin;
            _indicatorView.WL_centerX = selecteBtn.WL_centerX;
        }];
    }else if (_segmentStyle == WLSegmentTitleStyleCenterCircle){
        [UIView animateWithDuration:normal_indicator_trans_duration animations:^{
            [UIView animateWithDuration:normal_indicator_trans_duration *0.8f animations:^{
                _indicatorView.WL_centerX = selecteBtn.WL_centerX;
                _indicatorView.WL_width = selecteBtn.WL_width - 2*normal_button_margin;

            }];
        }];
    }
    
    
    //居中
    [self makeBtnAligmentCenter:selecteBtn];
}

//滚动标题
- (void)makeBtnAligmentCenter:(UIButton *)button{
    CGFloat offsetX = button.center.x - self.frame.size.width * 0.5 ;
    if (offsetX < 0) {//偏左
        offsetX = 0;
    }
    CGFloat viewMaxOffsetX = self.contentSize.width - self.frame.size.width;
    if (viewMaxOffsetX < offsetX) {
        offsetX = viewMaxOffsetX;
    }
    
    [self setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    
}


- (void)selecteTitleBtnGradualChangeWhenScrollViewDidScroll:(UIScrollView *)scrollview{
    NSInteger currentPage = scrollview.contentOffset.x/scrollview.bounds.size.width;
    NSInteger afterIndex = currentPage;
    NSInteger curIndex = _oldPosition;
    
    _oldPosition = currentPage;
    
    //变化后
    UIButton *afterBtn = self.storageArray[afterIndex];
    UIButton *curBtn = nil;
    
    if (curIndex < self.storageArray.count) {
        curBtn = self.storageArray[curIndex];
    }
    if (curIndex < 0) {
        curBtn = afterBtn;
    }
    
//    计算scale
    NSInteger afterScale = 1;
    NSInteger curScale = 0;
    
    if (_titleFontGradualChange) {
//        UIButton *firstButton = self.subviews.firstObject;
//        if (self.firstButton) {
//            firstButton.titleLabel.font = [UIFont systemFontOfSize:normal_font];
//        }
//        
        
        [UIView animateWithDuration:normal_indicator_trans_duration animations:^{
            curBtn.transform = CGAffineTransformMakeScale(curScale * normal_text_scale + 1, curScale * normal_text_scale + 1);
            afterBtn.transform = CGAffineTransformMakeScale(afterScale * normal_text_scale + 1, afterScale * normal_text_scale + 1);
        }];
        
    }
    
    
    
}


#pragma mark public 

- (void)changeTitleButtonPosition:(UIScrollView *)scrollView{
    NSInteger index = scrollView.contentOffset.x / self.frame.size.width;
    
    UIButton *btn = [self.storageArray objectAtIndex:index];
    [self sureSelectedBtnLocation:btn];
    
}

#pragma mark event response
- (void)didSelectTitleBtnAction:(UIButton *)sender{
    NSInteger index = sender.tag;
    if ([self.wl_delegate respondsToSelector:@selector(didSelectedSegmentTitle:atIndex:)]) {
        [self.wl_delegate didSelectedSegmentTitle:self atIndex:index];
    }
    
    [self sureSelectedBtnLocation:sender];
}


#pragma mar private
- (void)setupViews{
    //按钮
    CGFloat btn_height = self.frame.size.height - 4;
    CGFloat btn_x = 0;
    CGFloat btn_y = 0;
    if (!self.titleViewCannotScroll) {//可以滚动的
        for (int index = 0; index < self.titleArray.count; index ++) {
            self.titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            //        _titleBtn
            self.titleBtn.titleLabel.font = [UIFont systemFontOfSize:normal_font];
            
            self.titleBtn.tag = index;
            CGSize buttonSize = [self sizeOfText:_titleArray[index] font:[UIFont systemFontOfSize:normal_font] maxSize:CGSizeMake(MAXFLOAT, btn_height)];
            CGFloat btn_width = buttonSize.width + normal_button_margin*2;
            self.titleBtn.frame = CGRectMake(btn_x, btn_y, btn_width, btn_height);
            [self.titleBtn setTitle:_titleArray[index] forState:UIControlStateNormal];
            [self.titleBtn setTitleColor:self.titleColor forState:UIControlStateNormal];
            [self.titleBtn setTitleColor:self.titleSelectColor forState:UIControlStateSelected];
            [self.titleBtn addTarget:self action:@selector(didSelectTitleBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            
            btn_x += btn_width;
            
            if (index == 0) {
                [self didSelectTitleBtnAction:self.titleBtn];
                _oldPosition = 0;
            }
            
            
            [self.storageArray addObject:self.titleBtn];
            [self addSubview:self.titleBtn];
        }
        
        
        CGFloat ScrollWidth = CGRectGetMaxX(self.subviews.lastObject.frame);
        self.contentSize = CGSizeMake(ScrollWidth, self.frame.size.height);

    }else{ //不可以滚动的  就是屏幕宽度
        CGSize buttonSize = [self sizeOfText:@"中公教育" font:[UIFont systemFontOfSize:normal_font] maxSize:CGSizeMake(MAXFLOAT, btn_height)];
        CGFloat buttonW = buttonSize.width;
        CGFloat buttonMargin = ([UIScreen mainScreen].bounds.size.width-self.titleArray.count*buttonW)/(self.titleArray.count*2); //一份margin
        btn_x = buttonMargin;
        for (int index = 0; index < self.titleArray.count; index ++) {
            self.titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            self.titleBtn.titleLabel.font = [UIFont systemFontOfSize:normal_font];
            self.titleBtn.tag = index;
        
            self.titleBtn.frame = CGRectMake(btn_x, btn_y, buttonW, btn_height);
            [self.titleBtn setTitle:_titleArray[index] forState:UIControlStateNormal];
            [self.titleBtn setTitleColor:self.titleColor forState:UIControlStateNormal];
            [self.titleBtn setTitleColor:self.titleSelectColor forState:UIControlStateSelected];
            [self.titleBtn addTarget:self action:@selector(didSelectTitleBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            
            btn_x += buttonW + 2*buttonMargin;
            
            if (index == 0) {
                [self didSelectTitleBtnAction:self.titleBtn];
                _oldPosition = 0;
            }
            
            
            [self.storageArray addObject:self.titleBtn];
            [self addSubview:self.titleBtn];
        }
        self.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, self.frame.size.height);
        self.scrollEnabled = NO;
    }
    
    
   
    
    
    
    UIButton *first = self.subviews.firstObject;
    if (first) {
        self.firstButton = YES;
    }
    
//    文字缩放
//    if (self.scaleText) {
//        first.titleLabel.font = [UIFont systemFontOfSize:normal_font * (normal_text_scale + 1)];
//    }
    
    //指示器
    CGSize buttonSize = [self sizeOfText:first.titleLabel.text font:[UIFont systemFontOfSize:normal_font] maxSize:CGSizeMake(MAXFLOAT, self.frame.size.height)];
    if (self.scaleText) {
        self.indicatorView.WL_width = buttonSize.width * (1 + normal_text_scale);
    }else{
        self.indicatorView.WL_width = buttonSize.width;
    }
    self.indicatorView.WL_centerX = first.WL_centerX;
    self.indicatorView.WL_y = self.frame.size.height - 2*normal_indicator_height;
    self.indicatorView.WL_height = normal_indicator_height;
    [self addSubview:_indicatorView];
    
    
}

- (CGSize)sizeOfText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize{
    NSDictionary *dict = @{NSFontAttributeName:font};
    return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
}



#pragma mark setter
//.h
- (void)setTitleColor:(UIColor *)titleColor{
    if (!titleColor) {
        return;
    }else{
        _titleColor = titleColor;
        for(UIButton *btn in self.storageArray){
            [btn setTitleColor:titleColor forState:UIControlStateNormal];
        }
    }
}

- (void)setTitleSelectColor:(UIColor *)titleSelectColor{
    if (!titleSelectColor) {
        return;
    }else{
        _titleSelectColor = titleSelectColor;
        for(UIButton *btn in self.storageArray){
            [btn setTitleColor:titleSelectColor forState:UIControlStateSelected];
        }
    }
}

- (void)setIndicatorColor:(UIColor *)indicatorColor{
    if (!indicatorColor) {
        return;
    }else{
        _indicatorColor = indicatorColor;
        [self.indicatorView setBackgroundColor:indicatorColor];
    }
    
}


- (void)setTitleFontGradualChange:(BOOL)titleFontGradualChange{
    _titleFontGradualChange = titleFontGradualChange;
    
}


- (void)setSegmentBackImage:(UIImage *)segmentBackImage{
    if (!segmentBackImage) {
        return;
    }
    UIImageView *backImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.contentSize.width, self.WL_height)];
    backImage.contentMode = UIViewContentModeScaleToFill;
    [backImage setImage: segmentBackImage];
    [self addSubview:backImage];
    [self sendSubviewToBack:backImage];
    
}


-(void)setSegmentStyle:(WLSegmentTitleStyle)segmentStyle{
    if (!segmentStyle) {
        return;
    }
    
    UIButton *firstBtn = self.subviews.firstObject;
    if (segmentStyle == WLSegmentTitleStyleCenterCircle) {
        CGSize buttonSize = [self sizeOfText:firstBtn.titleLabel.text font:[UIFont systemFontOfSize:normal_font] maxSize:CGSizeMake(MAXFLOAT, self.frame.size.height)];
        self.indicatorView.WL_width = buttonSize.width + normal_button_margin;
        self.indicatorView.WL_centerX = firstBtn.WL_centerX;
        CGFloat indicatorViewHeight_c = buttonSize.height + 8;
        self.indicatorView.WL_height = indicatorViewHeight_c;
        self.indicatorView.WL_centerY = firstBtn.WL_centerY;
        
//        CALayer *layer = [[CALayer alloc]init];
//        layer.shadowColor = [UIColor purpleColor].CGColor;
//        layer.cornerRadius = 7;
//        layer.masksToBounds = YES;
        self.indicatorView.layer.cornerRadius = 7;
        self.indicatorView.layer.masksToBounds = YES;
//        self.indicatorView.layer.mask = layer;
        self.indicatorView.alpha = 0.8;
    }else if(segmentStyle == WLSegmentTitleStyleBottomIndicatorLine){
        /*直接走默认的效果**/
    }else if (segmentStyle == WLSegmentTitleStyleBackImage){
        
    }else if (segmentStyle == WLSegmentTitleStyleBottomIndicatorImage){
        
    }
    
}

#pragma mark getter

- (NSArray *)titleArray{
    if (!_titleArray) {
        _titleArray = [[NSArray alloc]init];
    }
    return _titleArray;
}

//- (UIButton *)titleBtn{
////    if (!_titleBtn) {
//        _titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
////        _titleBtn
//        _titleBtn.titleLabel.font = [UIFont systemFontOfSize:normal_font];
//        
////    }
//    return _titleBtn;
//}

- (UIView *)indicatorView{
    if (!_indicatorView) {
        _indicatorView = [[UIView alloc]init];
        //默认 线
        _indicatorView.backgroundColor = [UIColor colorWithRed:85/255.f green:210/255.f blue:208/255.f alpha:1];
    }
    return _indicatorView;
}

- (BOOL)isScaleText{
    if (_scaleText) {
        _scaleText = YES;
    }
    return _scaleText;
}

- (BOOL)isFirstButton{
    if(_firstButton){
        _firstButton = NO;
    }
    return _firstButton;
}

- (UIColor *)titleColor{
    if (!_titleColor) {
        _titleColor = [UIColor grayColor];
    }
    return _titleColor;
}

- (UIColor *)titleSelectColor{
    if (!_titleSelectColor) {
        _titleSelectColor = [UIColor colorWithRed:82/255.f green:234/255.f blue:219/255.f alpha:1.f];
    }
    return _titleSelectColor;
}

- (NSMutableArray *)storageArray{
    if (!_storageArray) {
        _storageArray = [[NSMutableArray alloc]initWithCapacity:35];
        
    }
    return _storageArray;
}
@end
